<?php
	
	// uploads images to the file system. For the moment, returns link to image. Updates the database table 'uploads'
	// for the moment, accepts .jpg, .gif, .bmp, .png formats and max 10MB per image. 

	$stitchid=$_POST['stitchid'];
	$thumbWidth=100;

	// connect to the database
	require('db_init.php');
	
	// validate the image

	$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // check file type. Does not accept zip file- yet.
	$max_filesize = 10000000; // Maximum filesize 10MB
	$upload_path = '/societies/cshotel/snapstitcher/uploaded/'; // user uploaded pictures
	
	// Get the name of the file (including file extension).
	$filename = $_FILES['userfile']['name'];
	
	// Get the extension from the filename. Lowercase!
	$ext = strtolower(substr($filename, strpos($filename,'.'), strlen($filename)-1)); 
 
	// Check if the filetype is allowed, if not DIE and inform the user.
	if(!in_array($ext,$allowed_filetypes))
		die('Snapstitcher only allows .jpg, .gif , .bmp and .png files.');
 
	// Now check the filesize, if it is too large then DIE and inform the user.
	if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
		die('The file you attempted to upload is too large.');
 
	// Check if we can upload to the specified path, if not DIE and inform the user.
	if(!is_writable($upload_path))
		die('You cannot upload to the specified directory, please CHMOD it to 777.');
	
	// increment the imageid counter
	$query = 'UPDATE count SET imagecount = LAST_INSERT_ID(imagecount+1)';
	mysql_query($query);
	
	// and safely retrieve this value
	$query = 'SELECT LAST_INSERT_ID()';
	$imageid = mysql_result( mysql_query($query), 0, 0);

	// prepare MySQL statement to update table if file copy is successful
	$query = "INSERT INTO uploads VALUES ($imageid, $stitchid)";
	
	// now attempt to copy the file into our storage directory, 
	if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $imageid . $ext))
		mysql_query($query);
	else
		die('There was an error during the file upload.  Please try again.');
	
	// now load the image
	switch($ext)
	{
		case '.gif': 
			$img = imagecreatefromgif( $upload_path . $imageid . $ext );
			break;
		case '.jpg':
			$img = imagecreatefromjpeg( $upload_path . $imageid . $ext );
			break;
		case '.bmp':
			$img = imagecreatefromwbmp( $upload_path . $imageid . $ext );
			break;
		case '.png':
			$img = imagecreatefrompng( $upload_path . $imageid . $ext );
			break;
	}
	
	// retrieve the image dimensions
	$width = imagesx( $img );$height = imagesy( $img );

	// calculate thumbnail size
	$new_width = $thumbWidth;
	$new_height = floor( $height * ( $thumbWidth / $width ) );

	// create a new temporary image
	$tmp_img = imagecreatetruecolor( $new_width, $new_height );

	// copy and resize old image into new image 
	imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

	// save thumbnail into a file
	imagejpeg( $tmp_img, $upload_path . $imageid . '_thumb.jpg' );
	
	// finally, output all the images that have been uploaded for our stitchid

	$query = "SELECT imageid FROM uploads WHERE stitchid='$stitchid'";
	
	$result = mysql_query( $query );
	
	while( $id = mysql_fetch_array( $result ) )
		echo( '<img alt="Image ID: ' . $id['imageid'] . '" src="scripts/thumb.php?imageid=' . $id['imageid'] . '" />  ' );
	
	// and then close the connection to the database
	mysql_close();
	
?>
